package com.example.webdome.service.impl;


import com.example.webdome.pojo.ImageInformation;
import com.example.webdome.pojo.Results;
import com.example.webdome.pojo.SpiderDto;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;

import java.util.List;


@Service
public class SpiderService {




    public SpiderDto getUrl(String jsonData1, String jsonData2, String imageName) {
        ObjectMapper objectMapper = new ObjectMapper();
        List<String> urls = new ArrayList<>(); // 初始化urls列表

        try {
            ImageInformation imageInformation1 = objectMapper.readValue(jsonData1, ImageInformation.class);
            ImageInformation imageInformation2 = objectMapper.readValue(jsonData2, ImageInformation.class);

            // 查找第一个数据集中包含imageName的结果并添加到urls列表
            findAndAddUrls(imageInformation1.getResults(), imageName, urls);

            // 查找第二个数据集中包含imageName的结果并添加到urls列表
            findAndAddUrls(imageInformation2.getResults(), imageName, urls);

            return new SpiderDto(imageName, urls);
        } catch (IOException e) {
            e.printStackTrace();
            return new SpiderDto(null, urls);
        }
    }

    private void findAndAddUrls(List<Results> resultsList, String imageName, List<String> urls) {
        for (Results result : resultsList) {
            if(urls.size()>=4){
                break;
            }
            if (result.getTrackCensoredName().contains(imageName)) {
                urls.add(result.getArtworkURL512());
            }
        }
    }
    public String getJsonPart(String responseBody){
        int jsonStart = responseBody.indexOf("{");
        int jsonEnd = responseBody.lastIndexOf("}") + 1;

        if (jsonStart >= 0 && jsonEnd > jsonStart) {
            return responseBody.substring(jsonStart, jsonEnd);

        }
        return " ";
    }
}
